﻿// 文件名：将引用用于类对象
// 创建时间：2021/6/22/星期二 22:33:34

#include <iostream>
using namespace std;

#include <string>
string version1(const string & s1, const string & s2);
const string & version2(string & s1, const string & s2); //have side effect副作用
//const string & version3(string & s1, const string & s2);//bad design
const string version4(string & s1, const string & s2);//bad design
int main()
{

	string input;
	string copy;
	string result;
	cout << "Enter a string: ";
	getline(cin, input);
	copy = input;
	cout << "Your string as entered: " << input << endl;
	//调用version1()
	result = version1(input, "***");
	cout << "Your string enhanced: " << result << endl;
	cout << "Your original string: " << input << endl;

	//调用version2()
	result = version2(input, "###");
	cout << "Your string enhanced: " << result << endl;
	cout << "Your original string: " << input << endl;

	//调用version4()
	result = version4(input, "@@@");
	cout << "Your string enhanced: " << result << endl;
	cout << "Your original string: " << input << endl;



	system("pause");
	return 0;
}
string version1(const string & s1, const string & s2)
{
	//s1是input的别名
	//s2的类型是const char*,函数要求的类型是const string，隐含了对s2的类型转换
	string temp;
	temp = s2 + s1 + s2;
	return temp;
}

const string & version2(string & s1, const string & s2)//有副作用
{
	//s1是input的别名，并且是可以修改的(非const)，此处会将input修改
	s1 = s2 + s1 + s2;
	return s1;
}

//const string & version3(string & s1, const string & s2)//bad design
//{
//	//temp是局部变量，不能够作为const返回，函数调用后会被释放，此外，返回的还是一个引用，这至少要保证返回值不被释放
//	string temp;
//	temp = s2 + s1 + s2;
//	//返回的是局部变量，数据不安全
//	return temp;
//}
const string version4(string & s1, const string & s2)//bad design
{
	string temp;
	temp = s2 + s1 + s2;
	//返回的是局部变量，数据不安全
	return temp;
}